﻿using System;
using System.Collections;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Drawing2D;


public partial class Captcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strString = "abcdefghijklmnopqrstuvwxyz0123456789";

        Bitmap image = new Bitmap(Server.MapPath("~/images/captcha.png"));
        Graphics g = Graphics.FromImage(image);
        Rectangle area = new Rectangle(0,0,image.Width-1, image.Height-1);
        Pen pen = new Pen(Color.SkyBlue);

        LinearGradientBrush lgBrush = new LinearGradientBrush(area, Color.White, Color.FromArgb(220,220,220), LinearGradientMode.Vertical);
        
        g.FillRectangle(lgBrush, area);
        g.DrawRectangle(pen, area);

        SolidBrush brush = new SolidBrush(Color.Black);
        Random random = new Random();
        int randomCharIndex = 0;
        char randomChar;
        int charPosition = 10;

        string captcha = "";
        for (int i = 0; i < 7; i++)
        {
            randomCharIndex = random.Next(0, strString.Length);
            randomChar = strString[randomCharIndex];
            g.DrawString(Convert.ToString(randomChar), new Font("arial", random.Next(16,25)), brush, charPosition, 10);
            charPosition += 17;
            captcha += Convert.ToString(randomChar);
        }
        Session["CAPTCHA_CODE"] = captcha;
        Response.ContentType = "image/jpeg";
        image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}
